package com.dimeina.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.jsp.tagext.TryCatchFinally;

/**
 * @author Michael 封装数据库连接 和 关闭类
 */

public class DatabaseUtil {
	// 数据库驱动程序
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/dimeina?useUnicode=true&characterEncoding=utf-8";
	private static final String USER = "root";
	private static final String PASSWORD = "root";

	/**
	 * 声明对象，在子类中一样可以调用，用protected很重要！
	 */
	// 声明连接对象
	protected Connection conn = null;
	// 声明一个语句对象
	protected PreparedStatement pstmt = null;
	// 声明结果集对象
	protected ResultSet rs = null;

	/**
	 * 获取数据库连接对象
	 */

	// 获得连接方法
	public Connection getConnection() {
		try {
			// 加载并注册数据驱动程序
			Class.forName(DRIVER);
			// 获取连接对象
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (ClassNotFoundException e) {
			System.out.println("数据库加载异常！");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("数据库连接异常！");
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("数据库连接其他异常！");
		}
		return conn;
	}

	// 关闭所有资源
	public static void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			System.out.println("释放资源异常！");
			e.printStackTrace();
		}
	}

	// 测试连接数据库

	/*public static void main(String[] args) {
		DatabaseUtil database = new DatabaseUtil();
		Connection conn = database.getConnection();
		System.out.println(conn);
	}*/

}
